package com.payment.strategy.factory;

import com.payment.strategy.annotation.Pay;
import com.payment.strategy.service.PayStrategy;
import com.payment.strategy.util.BeanUtil;
import org.reflections.Reflections;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * created by YDW
 */
public class PayStrategyFactory {

    /**
     * 单例构造函数
     */
    private PayStrategyFactory() {
    }

    private static class  Builder{
        private static  final  PayStrategyFactory payStrategyFactory=new PayStrategyFactory();
    }

    /**
     * 策略类文件
     */
    private static  final String PAY_STRATEGY_PACKAGE="com.payment.strategy.service";

    /**
     * 策略集合
     */
    private static  final Map<String,Class> STRATEGY_MAP=new HashMap<>();

    static {
        //使用扫描注解类类的包
        Reflections  reflections=new Reflections(PAY_STRATEGY_PACKAGE);
        Set<Class<?>> classes=reflections.getTypesAnnotatedWith(Pay.class);
        classes.forEach(item ->{
            Pay pay=item.getAnnotation(Pay.class);
            STRATEGY_MAP.put(pay.value(),item);
        });
    }

    public static PayStrategy getPayStrategy(String type){
        Class payItem=STRATEGY_MAP.get(type);
        if(StringUtils.isEmpty(payItem)){
            return  null;
        }
        return (PayStrategy) BeanUtil.getBean(payItem);
    }
}
